Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "D+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

$.formatDate = function (date, fmt) {
    var _this = date;
    var o = {
        "M+": _this.getMonth() + 1, //月份
        "D+": _this.getDate(), //日
        "h+": _this.getHours(), //小时
        "m+": _this.getMinutes(), //分
        "s+": _this.getSeconds(), //秒
        "q+": Math.floor((_this.getMonth() + 3) / 3), //季度
        "S": _this.getMilliseconds() //毫秒
    };
    if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

var genIdByField = function (field) {
    var id;
    var name = field.attr("name");
    if (name.indexOf("[") == -1) {
        id = name + field.index("[name='" + name + "']");
    } else {
        id = name.replace("[", "").replace("]", "");
    }
    return id.replace(/\./g, "-");
};

var SP = {};
SP.contexPath = "";
SP.url = function (url) {
    if (url.indexOf("http") > -1 || url.indexOf(SP.contexPath) > -1) {
        return url;
    }
    return SP.contexPath + url;
};
SP.render = function (url, args, callback) {
    var result;
    $.ajax(SP.url(url), {
        type: 'GET',
        async: callback ? true : false,
        cache: true,
        success: function (tpl) {
            result = Mustache.render(tpl, args);
            if (callback) {
                callback(result);
            }
        }
    });
    if (!callback) {
        return result;
    }
};

SP.findFunc = function (name, obj) {
    for (var p in obj) {
        var prop = obj[p];
        if (typeof(prop) == "function" && p.toString() == name) {
            return prop;
        }
    }
};

SP.modal = function (args) {
    var buttons = args.buttons || {};
    if (args.onSubmit) {
        buttons.submit = "确认";
    }
    if (!buttons.close && !buttons.submit) {
        args.buttons = null;
    } else {
        args.buttons = buttons;
    }

    var _dgDom = $(SP.render('/webjars/smartpage/templates/modal.html', args)).appendTo("body");
    var _dg = _dgDom.find(".modal-dialog");
    var _dgBody = _dgDom.find(".modal-body");

    if (args.height) {
        _dgBody.height(args.height);
    }

    if (args.url) {
        $iframe = $('<iframe />');
        $iframe.attr({
                src: SP.url(args.url),
                width: '100%',
                height: '100%',
                allowtransparency: 'yes',
                frameborder: 'no'
            })
            .on('load', function () {
                var callback = $iframe[0].contentWindow.oniframeloaded;
                if (callback) {
                    callback(args);
                }

                if (!args.height) {
                    var test;
                    try {
                        // 跨域测试
                        test = $iframe[0].contentWindow.frameElement;
                    } catch (e) {

                    }

                    if (test) {
                        setTimeout(function () {
                            var fh = $iframe.contents().find("body").height();
                            if (fh <= 0) {
                                fh = 400;
                            }
                            _dgBody.height(fh);
                        }, 100);
                    }
                }

            });
        _dgBody.append($iframe);

        _dg.find(".modal-footer .btn-primary").click(function () {
            _dgDom.trigger("modal.submit");
            if (args.onSubmit) {
                var frameFuc = SP.findFunc(args.onSubmit, $iframe[0].contentWindow);
                if (frameFuc) {
                    var _return = frameFuc(_dgDom);
                    var _return_type = typeof(_return);
                    if (_return_type == "object") {
                        var winFunc = SP.findFunc(_return[0], window);
                        if (winFunc) {
                            _return.shift();
                            winFunc.apply(this, _return);
                            _dgDom.modal("hide");
                        }
                    } else if (_return_type == 'boolean') {
                        if (_return) {
                            _dgDom.modal("hide");
                        }
                    }
                }
            }
        });
    } else {
        _dg.find(".modal-footer .btn-primary").click(function () {
            _dgDom.trigger("modal.submit");
            if (args.onSubmit) {
                var winFunc = SP.findFunc(args.onSubmit, window);
                winFunc.call(this, _dgDom);
            }
        });
    }

    if (args.width) {
        _dg.width(args.width);
    }

    _dgDom.content = function (content) {
        _dgBody.html(content);
    };
    return _dgDom;
};

SP.closeAllModal = function () {
    $(".modal").modal("hide");
};

SP.infoModal = function (info) {
    return SP.modal({"body": info, "width": 300});
};

SP.confirm = function (info, func) {
    var modal = window.confirmModal;
    if (!modal) {
        var args = {};
        args.title = "信息确认";
        args.body = info;
        args.buttons = {"submit": "确定", "close": "取消"};
        modal = SP.modal(args);
        modal.on("modal.submit", function () {
            modal.modal("hide");
            func();
        });
        window.confirmModal = modal;
    }
    modal.content(info);
    modal.modal("show");
};

SP.serializeMap = function (form) {
    var fieldMap = {};
    var tmp = {};
    $($(form).serializeArray()).each(function () {
        var ary = tmp[this.name];
        if (!ary) {
            ary = [];
            tmp[this.name] = ary;
        }
        ary.push(this.value);
    });
    for (v in tmp) {
        fieldMap[v] = tmp[v].join(",");
    }
    return fieldMap;
};

$(function () {

    //日期控件
    $(".laydate-date").each(function () {
        var layd = $(this);
        layd.addClass("datepicker");
        layd.attr("validateCondition", "isLaydateHidden()");
        var dateTime = layd.attr("value");
        var format = $(this).attr("format") || 'YYYY/MM/DD hh:mm';
        var istime = format.indexOf("hh") >= 0;
        var id = genIdByField(layd);
        layd.attr("id", id);
        var hiddenField = $("<input type='hidden' name='" + layd.attr("name") + "'/>").val(dateTime);
        layd.after(hiddenField).removeAttr("name");
        layd.val((dateTime && dateTime > 0) ? new Date(parseInt(dateTime)).format(format) : "");
        var config = {
            elem: "#" + id,
            istime: istime,
            format: format,
            choose: function (datas) { //选择日期完毕的回调
                hiddenField.val(datas == '' ? '' : new Date(datas).getTime());
                layd.validationEngine('validate');
            }
        };
        var min = $(this).attr("min");
        if (min) config = $.extend(config, {min: laydate.now(min)});
        laydate(config);
    });

    $("[fake-delete-id]").live("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        var _this = $(e.target);
        SP.confirm("确定要删除此纪录吗?", function () {
            var _id = _this.attr("fake-delete-id");
            var _class = _this.attr("fake-delete-class");
            var _parentLookUp = _this.attr("parent-look-up");
            $.post(SP.url("/sp/fakeDelete"), {id: _id, className: _class}, function () {
                if (_parentLookUp) {
                    _this.closest(_parentLookUp).detach();
                } else {
                    location.reload();
                }
            });
        });
    });

    $("[ajax-submit-reload]").live("click", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var _form = $(this).closest("form");
        var _action = _form.attr("action");
        var _reload = $(this).attr("ajax-submit-reload");
        $.post(_action, _form.serialize(), function () {
            if (_reload == "true") {
                location.reload();
            } else {
                var modal = SP.infoModal("保存成功");
                modal.modal("show");
                setTimeout(function () {
                    modal.modal("hide");
                }, 500)
            }
        });
    });
});